#!/usr/bin/perl 

# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Bookstore.pm
# Copyright (c) 2004 Daniel J Shahin
# All rights reserved.
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License,
# Version 2, as published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
#
# Copies of the GNU General Public License are available from
# the Free Software Foundation website, http://www.gnu.org/.
#
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

package POS;

#use strict;
use URI::Escape;
use base CGI::Application;
use base CGI::Application::Plugin::Session;
use CGI::Carp qw(fatalsToBrowser);
use Date::Calc qw(Today Delta_Days Add_Delta_YM);
use HTML::Template;
use DBI;

sub setup {
    my $self = shift;
    $self->error_mode('error');
    $self->start_mode('front_page');
    $self->mode_param('rm');
    $self->run_modes(
        'front_page' => 'front_page',
        'login'      => 'login',
        'logout'     => 'logout',
        'browse'     => 'browse',
        'search'     => 'search',
        'cal'        => 'cal',
        'register'   => 'register',
    );

}

sub cgiapp_init {
    my $self = shift;
    my $q    = $self->query();
    my $rm   = $q->param('rm');
    $self->{dbh} = DBI->connect(
        $self->param('database'),
        $self->param('dbuser'),
        $self->param('dbpass')
    ) || croak "can't connect:$!";
    my $dbh        = $self->{dbh};
    my $cookiename = $self->param(storename) . 'store';
    CGI::Session->name( $self->param(storename) . 'store' );
    $self->session_config(
        CGI_SESSION_OPTIONS => [
            $self->param('database'), $q,
            { DataSourec => $self->param('datasource') }
        ],
        COOKIE_PARAMS => {
            -path    => '/',
            -name    => $cookiename,
            -expires => '+3M',
        },
        SEND_COOKIE => 1,
    ) || croak "can't get session:$!";
    my $session = $self->session();

    if ( $q->param('op') eq 'rss' ) {
        print "Content-Type: text/xml\n\n";
    }
    elsif ( $q->param('op') eq 'js' ) {
        print "Content-Type: text/javascript\n\n";
    }
    elsif ( $q->param('op') eq 'nh' ) {

        #don't print headers for certain run modes
    }
    else {
        print $self->session->header( $self->session->cookie );
    }
}

sub cgiapp_prerun {
    my $self     = shift;
    my $q        = $self->query();
    my $session  = $self->session();
    my $rm       = $q->param('rm');
    my $rm_perms = $self->{rm_perms};
    unless ( $self->session->param('~logged-in') == 1 ) {
        $self->prerun_mode('login');
    }
}

sub teardown {
    my $self = shift;
    my $dbh  = $self->{dbh};
    $dbh->disconnect;
}

sub logout {
    my $self     = shift;
    my $q        = $self->query();
    my $session  = $self->session();
    my $template = $self->load_tmpl( 'login.tmpl.html', cache => 1 );
    $self->session->param( '~logged-in', 0 );
    $self->session_delete;
    $self->login;

    #print $template->output();
    exit;
}

sub login {
    my $self    = shift;
    my $q       = $self->query();
    my $dbh     = $self->{dbh};
    my $session = $self->session();
    my $bm      = $q->param('bm');
    if ( $q->param('login') && $q->param('pass') ) {
        my $sth = $dbh->prepare(
"select login, pass, perm_level, fname, lname, id as hid from passwd where login=\""
              . $q->param('login')
              . "\"" );
        $sth->execute();
        my ( $login, $pass, $perm_level, $fname, $lname, $id ) =
          $sth->fetchrow_array;

        #if ( ( $pass ne '' ) && ( $pass eq $q->param('pass') ) ) {
        if ( ( $pass ne '' ) && ( crypt( $q->param('pass'), $pass ) eq $pass ) )
        {

            $self->{headercheck} = 1;

            #set session parameters
            $self->session->param( '~logged-in', 1 );
            $self->session->param( 'perm_level', $perm_level );
            $self->session->param( 'store_name', $self->param(storename) );
            $self->session->param( 'hid',        $id );
            $self->session->param( 'fname',      $fname );
            $self->session->param( 'lname',      $lname );
            my $hname = $login;
            $session->param( 'hijinx_name', $hname );
            $session->param( 'real_ip',     $ENV{'HTTP_X_FORWARDED_FOR'} );
            $self->front_page();
            exit;
        }
        else {
            my $template = $self->load_tmpl( 'login.tmpl.html', cache => 1 );
            print $template->output();
            exit;
        }

    }
    else {
        my $template = $self->load_tmpl( 'login.tmpl.html', cache => 1 );

        print $template->output();
        exit;
    }
    exit;
}

sub error {
    my $self     = shift;
    my $template = $self->load_tmpl( "$template_path/error.tmpl.html",
        die_on_bad_params => 0 );
    $template->param( error => $@ );
    $template->param( $self->session->param_hashref() );
    print $template->output();
    exit;
}

sub front_page {
    my $self     = shift;
    my $template = $self->load_tmpl( "$template_path/basic.tmpl.html",
        die_on_bad_params => 0 );

    #$template->param( error => $@ );
    $template->param( $self->session->param_hashref() );
    print $template->output();
    exit;
}

sub cal {
    my $self     = shift;
    my $template = $self->load_tmpl( "$template_path/cal.tmpl.html",
        die_on_bad_params => 0 );
    $template->param( $self->session->param_hashref() );
    print $template->output();
    exit;
}

sub register {
    my $self     = shift;
    my $template = $self->load_tmpl( "$template_path/register.tmpl.html",
        die_on_bad_params => 0 );
    $template->param( $self->session->param_hashref() );
    print $template->output();
    exit;
}

sub customers {
    my $self     = shift;
    my $template = $self->load_tmpl( "$template_path/register.tmpl.html",
        die_on_bad_params => 0 );
    $template->param( $self->session->param_hashref() );
    print $template->output();
    exit;
}

sub search {
    my $self = shift;
    my $q    = $self->query;
    my $type = $q->param('type');
    my $term = $q->param('term') || '%';
    my ( $results, $results_template, $results_output, $num_results );
    if ( $type eq "customers" ) {
        $results          = $self->customer_search($term);
        $num_results      = @$results;
        $results_template = $self->load_tmpl(
            "$template_path/results/customers.tmpl.html",
            die_on_bad_params => 0,
            loop_context_vars => 1
        );
        $results_template->param(
            CUSTOMERS => $results,
            NUM       => $num_results,
            TERM      => $term
        );
        $results_output = $results_template->output();

        #croak $results_output;
    }
    elsif ( $type eq "subscribers" ) {
        $results          = $self->subscriber_search($term);
        $results_template = $self->load_tmpl(
            "$template_path/results/customers.tmpl.html",
            die_on_bad_params => 0,
            loop_context_vars => 1
        );
        $results_template->param( CUSTOMERS => $results );
        $results_output = $results_template->output();
    }
    elsif ( $type eq "products" ) {
        $results          = $self->product_search($term);
        $num_results      = @$results;
        $results_template = $self->load_tmpl(
            "$template_path/results/products.tmpl.html",
            die_on_bad_params => 0,
            loop_context_vars => 1
        );
        $results_template->param(
            PRODUCTS => $results,
            NUM      => $num_results,
            TERM     => $term
        );
        $results_output = $results_template->output();
    }
    else {
        croak "don't know that search mode yet";
    }

    my $template = $self->load_tmpl( "$template_path/results.tmpl.html",
        die_on_bad_params => 0 );
    $template->param( $self->session->param_hashref() );
    $template->param( RESULTS => $results_output );
    print $template->output();
    exit;
}

sub customer_search {
    my $self = shift;
    my $term = shift;
    $order = "fname";
    $term  = "\%$term\%";
    my $dbh = $self->{dbh};
    my $sth = $dbh->prepare(
"select * from customers where fname like ? or lname like ? order by fname, lname"
    );
    $sth->execute( $term, $term ) || croak "can't execute" . $sth->errstr;
    my @customers;

    while ( my $cust = $sth->fetchrow_hashref ) {
        $cust->{'fname'} = ucfirst( $cust->{'fname'} );
        $cust->{'lname'} = ucfirst( $cust->{'lname'} );
        push @customers, $cust;
    }
    return \@customers;
}

sub product_search {
    my $self = shift;
    my $term = shift;
    $term = "\%$term\%";
    my $dbh = $self->{dbh};
    my $sth =
      $dbh->prepare("select * from products where name like ? order by name");
    $sth->execute($term) || croak "can't execute" . $sth->errstr;
    my @products;
    while ( my $prod = $sth->fetchrow_hashref ) {
        push @products, $prod;
    }
    return \@products;
}

sub subscriber_search {
    my $self = shift;
    my $term = shift;
    $term = "\%$term\%";
    my $dbh = $self->{dbh};
    my $sth = $dbh->prepare(
"select * from customers where fname like ? or lname like ? and frozen = '0'  order by fname,lname"
    );
    $sth->execute( $term, $term ) || croak "can't execute" . $sth->errstr;
    my @customers;
    while ( my $cust = $sth->fetchrow_hashref ) {
        push @customers, $cust;
    }

    return \@customers;
}

sub today {
    $gmt = gmtime();
    my ( $year, $month, $day ) = Today($gmt);
    $year =~ s/\d\d(\d\d)/$1/;
    if ( $month < 10 ) { $month = 0 . $month }
    if ( $day < 10 )   { $day   = 0 . $day }
    $today = $year . $month . $day;

}

1
